let soundRecording = {
    recorder: null,
    config: {
        control: 0,
        type: 'mp3'
    },
    isStart: false,
    initAction: function (config) {
        let _this = this
        _this.recorder = new Recorder();
        if(!!config) {
              _this.config = {
                ..._this.config,
                ...config,
                type: config.type || 'mp3'
            }
        }
        let lastTimestamp = 0
        let time = 0
        let flag = 0
        _this.recorder.onprogress = function (params) {

            let fileSize = Number((params.fileSize / 1024 / 1024).toFixed(2))
            let duration = Number(params.duration.toFixed(2))

            let maxFileSize = 8 * 1024 * 1024
            if (params.fileSize > maxFileSize) {
                _this.recStop(true)
                _this.recStart(true)
                console.log('=========上传')
                return
            }

            let vol = params.vol
            if ( _this.config.control == 1) { 

                // 音量大于30播放
                if (vol >= 30) {
                    time = duration
                    if (flag == 2) {
                        _this.recorder.resume()
                        flag = 1
                    }
                }
                // 音量小于30超过3秒停止播放
                if (vol <= 30 && duration - time >= 3 && flag == 1) {
                    _this.recorder.pause()
                    flag = 2
                }
            } else {
                let timestamp = new Date().getTime();
                if ((timestamp - lastTimestamp) < 2000) return
                lastTimestamp = timestamp
            }

            console.log(vol, '=====', '录音大小(M)：', fileSize, ' ==== 录音时长(秒)：', duration);

        }

        return new Promise((resolve) => {
            console.log(_this)
            resolve(true)
        })
    },
    /**
    * 开始录音
    */
    recStart: async function (restart) {
        let _this = this
        if (!_this.recorder) {
           await _this.initAction(_this.config)
        }

        _this.recorder.start().then(() => {
            if(!restart) {
                console.log('=====开始录音')
                alert('开始录音');
            }
            
            _this.isStart = true
        }, (error) => {
            if (!error) return
            let errInfo = `${error.name} : ${error.message}`
            console.log(errInfo);
            alert(error.message);
            _this.recDestroy()
        });
    },
    /**
     * 停止录音
     */
    recStop: async function(restart) {

        if (!this.isStart) {
            console.log('还未开始录音')
            alert('还未开始录音');
            return
        }

        if(!restart) {
            await this.delayedTime(300)
            // Toast.loading('上传中...', 60)
        }
    
        let blob = this.recorder.getWAVBlob();
        console.log('blob====',blob)
        let duration = Number(this.recorder.duration)
        let durationTime = duration.toFixed(2)
        let timestamp = new Date().getTime()
        let file = new window.File([blob], `${timestamp}-${durationTime}.wav`, { type: 'audio/wav' })

        if (this.config.type == 'mp3') {
            let dataView = this.recorder.getWAV()
            const mp3Blob = this.convertToMp3(dataView);
            file = new window.File([mp3Blob], 'mp3Blob.mp3', { type: 'audio/mp3' })
            // console.log(mp3Blob, file)
        }

        console.log('file====',file)

        // this.recDestroy()
    },
    /**
     * 播放录音
     */
    recPlay: function () {
        if (!this.isStart) {
            alert('还未开始录音');
            return
        }
        this.recorder.play();
    },
    /**
     * 销毁录音实例，置为null释放资源，fn为回调函数
     */
    recDestroy: function () {
        let _this = this

        _this.recorder.destroy().then(function () {
            _this.recorder = null;
        });
    },
    /**
     * 转化为mp3格式
     */
    convertToMp3: function (wavDataView) {
        // 获取wav头信息
        const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
        const { channels, sampleRate } = wav;
        console.log('wav', wav)
        const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
        // 获取左右通道数据
        const result = this.recorder.getChannelData()
        const buffer = [];

        const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
        const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
        const remaining = leftData.length + (rightData ? rightData.length : 0);

        const maxSamples = 1152;
        for (let i = 0; i < remaining; i += maxSamples) {
            const left = leftData.subarray(i, i + maxSamples);
            let right = null;
            let mp3buf = null;

            if (channels === 2) {
                right = rightData.subarray(i, i + maxSamples);
                mp3buf = mp3enc.encodeBuffer(left, right);
            } else {
                mp3buf = mp3enc.encodeBuffer(left);
            }

            if (mp3buf.length > 0) {
                buffer.push(mp3buf);
            }
        }

        const enc = mp3enc.flush();

        if (enc.length > 0) {
            buffer.push(enc);
        }
        return new Blob(buffer, { type: 'audio/mp3' });
    },
    delayedTime(time) {
        return new Promise((resolve) => {
            setTimeout(()=> {
                resolve()
            },time)
        })
    }

}

// export default soundRecording